package com.java1412.web.controller.api;

import com.java1412.common.utils.ConstantUtil;
import com.java1412.common.utils.R;
import com.java1412.common.utils.ResponseEnum;
import com.java1412.web.utils.GenerateVerifyCodeUtil;
import com.java1412.web.utils.SmsUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 发送验证码的接口
 *
 * @author java1412
 * @since 2025-05-16 16:06
 */
@RestController
@RequestMapping(value = "/api/sendCode")
public class ApiSendCodeController {

    @Resource
    private GenerateVerifyCodeUtil generateVerifyCodeUtil;

    @Resource
    private SmsUtil smsUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public R sendCode(
            @RequestParam(value = "phone") String phone
    ) {
        // 生成验证码
        String code = generateVerifyCodeUtil.generate4Code();
        // 生成uuid，作为redis的key
        String reqId = UUID.randomUUID().toString().replaceAll("-", "");
        // 发送验证码,注释这行代码，项目上线需要放开
        // smsUtil.send4Code(reqId, phone, code);
        // 控制台打印
        System.out.println(reqId + ":" + phone + "-" + code);
        // 将验证码和手机号设置到redis中，并设置过期时间
        // 格式reqId作为key，手机号-验证码作为value
        stringRedisTemplate.opsForValue().set(reqId, phone + "-" + code);
        stringRedisTemplate.expire(reqId, ConstantUtil.CODE_TIME_OUT, TimeUnit.MINUTES);
        return R.r(ResponseEnum.USER_SEND_VERIFY_CODE_SUCCESS, reqId);
    }
}
